<style lang="scss" src="./index.scss" scoped></style>
<template>
    <div class="auth-login-box enter">
        <div class="auth-login__body">
            <auth-card>
                <div class="login-type">
                    <el-tabs v-model="activeName" class="login-type-select">
                        <el-tab-pane label="账号密码登录" name="1" />
                        <el-tab-pane label="手机验证码登录" name="2" />
                    </el-tabs>
                </div>
                <div class="auth-login__form-box" v-if="activeName === '1'">
                    <validation-observer ref="observerRef" slim>
                        <el-form
                            class="transparent-form"
                            label-width="0"
                            ref="formRef"
                            @keyup.enter.native="update"
                        >
                            <validation-provider
                                name="model.username"
                                :rules="'required'"
                                :customMessages="{ required: '请输入账号名' }"
                                slim
                            >
                                <el-form-item required>
                                    <div class="cf__group">
                                        <div class="cf__group-info">
                                            <el-input
                                                v-model.trim="model.username"
                                                name="model.username"
                                                placeholder="请输入账号名"
                                                maxlength="30"
                                                auto-complete="off"
                                            >
                                                <!-- <div class="cf__group-info-icon user" slot="prefix"></div> -->
                                                <div
                                                    class="cf__group-info-icon"
                                                    slot="prefix"
                                                >
                                                    <icon-svg
                                                        name="icon-fill-user"
                                                    ></icon-svg>
                                                </div>
                                            </el-input>
                                        </div>
                                    </div>
                                </el-form-item>
                            </validation-provider>
                            <validation-provider
                                name="model.password"
                                :rules="'required'"
                                :customMessages="{ required: '请输入密码' }"
                                slim
                            >
                                <el-form-item required>
                                    <div class="cf__group">
                                        <div class="cf__group-info">
                                            <el-input
                                                type="password"
                                                v-model.trim="model.password"
                                                name="model.password"
                                                placeholder="请输入密码"
                                                maxlength="30"
                                                auto-complete="off"
                                            >
                                                <!-- <div class="cf__group-info-icon pass" slot="prefix"></div> -->
                                                <div
                                                    class="cf__group-info-icon"
                                                    slot="prefix"
                                                >
                                                    <icon-svg
                                                        name="icon-fill-lock"
                                                    ></icon-svg>
                                                </div>
                                            </el-input>
                                        </div>
                                    </div>
                                </el-form-item>
                            </validation-provider>
                            <el-form-item>
                                <div class="cf__group">
                                    <div class="cf__group-info flex-end">
                                        <el-button
                                            class="auth-login__form-btn-text"
                                            @click="handleForgetClick"
                                            type="text"
                                        >
                                            忘记密码
                                        </el-button>
                                    </div>
                                </div>
                            </el-form-item>
                            <!-- <auth-tip ref="authTipRef"></auth-tip> -->
                            <el-form-item>
                                <el-button
                                    class="auth-login__form-btn"
                                    type="primary"
                                    :loading="btnLoader"
                                    @click="update"
                                >
                                    {{ btnLoader ? "登录中" : "登录" }}
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </validation-observer>
                </div>
                <div class="auth-login__form-box" v-else>
                    <validation-observer ref="observerRef" slim>
                        <el-form
                            class="transparent-form"
                            label-width="0"
                            ref="formRef"
                            @keyup.enter.native="update('phoneLogin')"
                        >
                            <validation-provider
                                name="model.phone"
                                :rules="'required'"
                                :customMessages="{ required: '请输入手机号' }"
                                slim
                                ref="phoneForm"
                            >
                                <el-form-item required>
                                    <div class="cf__group">
                                        <div class="cf__group-info">
                                            <el-input
                                                v-model.trim="model.phone"
                                                name="model.phone"
                                                placeholder="请输入手机号"
                                                maxlength="30"
                                                auto-complete="off"
                                            >
                                                <!-- <div class="cf__group-info-icon user" slot="prefix"></div> -->
                                                <div
                                                    class="cf__group-info-icon"
                                                    slot="prefix"
                                                >
                                                    <icon-svg
                                                        name="icon-fill-phone"
                                                    ></icon-svg>
                                                </div>
                                            </el-input>
                                        </div>
                                    </div>
                                </el-form-item>
                            </validation-provider>
                            <validation-provider
                                name="model.smscode"
                                :rules="'required'"
                                :customMessages="{ required: '请输入验证码' }"
                                slim
                            >
                                <el-form-item required>
                                    <div class="cf__group">
                                        <div class="cf__group-info flex">
                                            <el-input
                                                v-model.trim="model.smscode"
                                                name="model.captcha"
                                                placeholder="请输入验证码"
                                                maxlength="6"
                                                auto-complete="off"
                                            >
                                                <div
                                                    class="cf__group-info-icon"
                                                    slot="prefix"
                                                >
                                                    <icon-svg
                                                        name="icon-fill-message"
                                                    ></icon-svg>
                                                </div>
                                            </el-input>
                                            <captcha-btn
                                                :stop="countDownBtn"
                                                class="captcha-box"
                                                :phone="model.phone"
                                                @on-send="handleSend"
                                                regCheck
                                                ref="captchaBtn"
                                            ></captcha-btn>
                                        </div>
                                    </div>
                                </el-form-item>
                            </validation-provider>
                            <!-- <auth-tip ref="authTipRef"></auth-tip> -->
                            <el-form-item>
                                <el-button
                                    class="auth-login__form-btn"
                                    type="primary"
                                    :loading="btnLoader"
                                    @click="update('phoneLogin')"
                                >
                                    {{ btnLoader ? "登录中" : "登录" }}
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </validation-observer>
                </div>
                <div class="wechat-login-box">
                    <p>第三方登录</p>
                    <div @click="handleWechat">
                        <img src="~@/assets/wechat.png" alt="wechat" />
                        <img src="~@/assets/wechat-hover.png" alt="wechat" />
                        <p>微信登录</p>
                    </div>
                </div>
            </auth-card>
            <fixed-btn></fixed-btn>
        </div>
        <footer-info></footer-info>
    </div>
</template>

<script lang="ts">
import { ValidationObserver, ValidationProvider } from "vee-validate";
import FixedBtn from "@/views/auth/src/components/fixed-btn/index.vue";
import AuthCard from "../components/card/index.vue";
import CaptchaBtn from "../components/captcha-btn/index.vue";
import FooterInfo from "../components/footer-info/index.vue";
import AuthTip from "../components/auth-tip/index.vue";
import { Component, Mixins } from "vue-property-decorator";
import AuthCommonMixin from "../../common.mixin";
import FormMixin from "@/mixins/form.mixin.base.ts";
import { State } from "vuex-class";
interface Model {
    username: string;
    password: string;
    captcha: string;
    uuid: string;
    captchaUrl: string;
    phone: string;
    smscode: string;
}

interface CaptchaMsg {
    result: boolean;
    msg: string;
}

@Component({
    name: "loginNotAlive",
    components: {
        ValidationProvider,
        ValidationObserver,
        AuthCard,
        CaptchaBtn,
        FooterInfo,
        AuthTip,
        FixedBtn
    }
})
export default class Login extends Mixins(AuthCommonMixin, FormMixin) {
    btnLoader = false;
    pageEnter = false;
    countDownBtn = true;
    activeName = "1";
    model: Model = {
        // username: 'admin',
        username: "",
        // password: '123456aa',
        password: "",
        captcha: "",
        uuid: "",
        captchaUrl: "",
        phone: "",
        smscode: ""
    };

    @State("user.userInfo") user: any;

    created() {
        const queryURLParams = (url: string) => {
            const params = {};
            let arr = url.split("?");
            if (arr.length <= 1) {
                return params;
            }
            arr = arr[1].split("&");
            for (let i = 0, l = arr.length; i < l; i++) {
                const a = arr[i].split("=");
                params[a[0]] = a[1];
            }
            return params;
        };
        const data: any = queryURLParams(window.location.href);
        if (data.code && data.state) {
            const code = data.code;
            const state = data.state;
            localStorage.removeItem("wxstate");
            localStorage.removeItem("wxcode");
            localStorage.wxstate = state;
            localStorage.wxcode = code;
            this.onSubmit({
                code,
                state
            });
        }
    }

    mounted() {
        // this.formatCaptcha();
        this.$nextTick(() => {
            setTimeout(() => {
                this.pageEnter = true;
            }, 500);
        });
    }

    async update() {
        if (this.btnLoader) return;
        const observerRef: any = this.$refs.observerRef;
        const validateResult: any = await observerRef.validate();

        if (validateResult) {
            this.onSubmit();
            return;
        }
        for (const key in observerRef.errors) {
            if (Object.prototype.hasOwnProperty.call(observerRef.errors, key)) {
                const cur: any = observerRef.errors[key];
                if (cur.length > 0) {
                    this.triggerMsg("el-icon-warning", cur[0]);
                    break;
                }
            }
        }
    }

    async onSubmit(obj?: any) {
        this.btnLoader = true;
        const self = this;
        let response;
        if (obj) {
            const { code, state } = obj;
            response = await this.$store.dispatch("login", {
                wxcode: code,
                wxstate: state,
                type: "2",
                jump() {
                    self.$router.push({ path: "bind-account" });
                }
            });
        } else if (this.activeName === "2") {
            const { phone, smscode } = this.model;
            response = await this.$store.dispatch("login", {
                phone,
                smscode,
                type: "3"
            });
        } else {
            const { username, password, captcha, uuid } = this.model;
            response = await this.$store.dispatch("login", {
                username,
                password,
                captcha,
                uuid,
                type: "1"
            });
        }
        if (
            this.responseHasError(response, (res: any) => {
                this.$message.error((res.data ? res.data.message : res.message) || "接口请求错误!");
            })
        ) {
            this.btnLoader = false;
            return;
        }
        this.$nextTick(() => {
            const redirectUrl: string = (this.$route.query.redirect || "") + "";
            // console.log(redirectUrl);
            if (redirectUrl) {
                this.$router.replace({ path: redirectUrl }).catch(() => {
                    this.btnLoader = false;
                    // this.triggerMsg("el-icon-warning", "获取菜单失败!");
                });
            }

            this.$store
                .dispatch("dynamicMenuRouter", true)
                .then(() => {
                    this.$store.dispatch("defaultPage").then((url: any) => {
                        this.$router.replace({ path: url }).catch(() => {
                            this.btnLoader = false;
                            // this.triggerMsg("el-icon-warning", "获取菜单失败!");
                        });
                    });
                })
                .catch((e: any) => {
                    this.triggerMsg("el-icon-warning", e);
                });
            // this.$router.replace({ name: "home" }).catch(() => {
            //     this.btnLoader = false;
            //     this.triggerMsg("el-icon-warning", "获取菜单失败!");
            // });
        });
    }

    handleForgetClick() {
        this.$router.push({
            path: "/auth/forget"
        });
    }

    async handleWechat() {
        const rs = await this.$server["user/wxOpen"]();
        // window.open(data, 'target');
        window.location.href = rs.data.data;
    }

    async handleSend(data: CaptchaMsg) {
        // 输入手机号格式不正确
        if (!data.result) {
            this.triggerMsg("el-icon-warning", data.msg);
            return false;
        }

        this.btnLoader = true;
        const response = await this.$server["user/sendSmsCode"]({
            data: {
                username: this.model.phone
            }
        });
        if (response.data.code === 200) {
            this.triggerMsg("el-icon-circle-check", "验证码已发送！");
        } else {
            this.$message.error(response.data.message || "接口请求错误!");
        }
        this.btnLoader = false;
        this.responseHasError(response, (res: any) => {
            if (res.data.code !== 200) {
                this.triggerMsg(
                    "el-icon-warning",
                    (res.data ? res.data.message : res.message) ||
                        "接口请求错误!"
                );
                (this.$refs.captchaBtn as any).clear();
            }
        });
    }
}
</script>

<style scoped lang="scss">
.auth-card-box {
    width: 532px;
    background: rgba(255, 255, 255, 0.7);
    border-radius: 19px;
    padding: 0.4rem 0 0.3rem 0;
    ::v-deep {
        .auth-card__main {
            width: 100%;
        }
    }
}

.login-type {
    .login-type-select {
        width: 398px;
        margin: 21px auto 0;
        ::v-deep {
            .el-tabs__item {
                width: 199px;
                text-align: center;
                height: 50px;
                line-height: 50px;
                padding: 0;
                font-size: 14px;
                font-weight: 500;
            }
            .el-tabs__active-bar {
                width: 190px;
            }
            .el-tabs__header {
                margin: 0;
            }
        }
    }
}

.auth-login-box {
    ::v-deep {
        .auth-login__form-box {
            // padding-top: 0;
        }
    }
}
</style>
